const path = require('path')
const fs = require('fs')
const {
  getPathfromcwd,
  copyPublicToDist,
  writeJs,
} = require('./utils/index.js')
const { insertScriptToHtml } = require('./utils/insertHtml.js')
const { renderTemplateMap } = require('./utils/renderTemplateMap.js')
const { startliveServer } = require('./utils/liveServer.js')
const { genTerserCode } = require('./utils/genTerserCode.js')
const { getResourceQueue } = require('./utils/getResourceQueue.js')

const configFileName = './minipack.config.js'
// 获取config文件
const config = require(getPathfromcwd(configFileName))
const { entry, template, outputPath, publicPath } = config
// 拷贝public目录
copyPublicToDist(publicPath, outputPath, template)
// 读取html文件，写入script
const templateHtml = fs.readFileSync(template, { encoding: 'utf-8' })
fs.writeFileSync(
  path.join(outputPath, './index.html'),
  insertScriptToHtml(templateHtml),
  { encoding: 'utf-8' }
)
// 读取入口文件，生成文件图结构
const queue = getResourceQueue(entry)
// 使用terser丑化代码输出带指定目录
const outputJs = async () => {
  const templateCode = renderTemplateMap(queue)
  // const tenserCode = await genTerserCode(templateCode)
  writeJs(templateCode, outputPath)
  // 打开liveServer
  // startliveServer(outputPath)
}
outputJs()

